#include <iostream>
#include <ace/SOCK_Connector.h>
#include <ace/Time_Value.h>
#include "GTASender.h"
#include "GTASenderMgr.h"
#include "GTATradeProvider.h"
#include "LogHelper.h"



namespace gta
{
	CGTASender::CGTASender(std::string key, std::string addr,int port ,CGTATradeProvider* pProvider)
	{
		m_addr = addr;
		m_port = port;
		m_key = key;
		m_pdata = NULL;
		m_pProvider = pProvider;

		m_trytimes = 0;
	}

	void CGTASender::Dispose()
	{
		this->m_pProvider->GetCGTASenderMgr()->RemoveSender(this->GetKey());
	}	

	int CGTASender::svc()
	{
		return OldSenddataJob();
	}

	int CGTASender::OldSenddataJob()
	{
		static ACE_Time_Value TIMEOUT = ACE_Time_Value(3);
		ACE_SOCK_Connector conc;
		

		ACE_INET_Addr port_to_listen(m_port,m_addr.c_str());
		char addr[32];
		strcpy(addr,m_addr.c_str());

		ACE_SOCK_Stream pstream;
		if( conc.connect(pstream,port_to_listen))
		{
			WriteLog("stdout",LTALL," try reconnect %s : %d but still failed " ,m_addr.c_str(),m_port);
			return -1;
		}

		int len = pstream.send(m_pdata,m_datalen,&TIMEOUT);
		this->m_pProvider->GetShareDataPool()->Push(m_pdata);
		Dispose();
		return 0;
	}

	std::string CGTASender::GetKey() const
	{
		return m_key;
	}

	bool CGTASender::SendData(char * pdata,int len )
	{		
		m_datalen = len;
		m_pdata = pdata;
		this->svc();
		return true;
	}


	CGTASender::~CGTASender()
	{
	}
}